package com.mobdev.notepadgdocs;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.preference.ListPreference;
import android.provider.Settings;
import android.util.AttributeSet;
import android.view.View;

public class SelectGoogleAccountPreference extends ListPreference
{
    // This is the constructor called by the inflater
    public SelectGoogleAccountPreference(Context context, AttributeSet attrs) {
        super(context, attrs);

        updateAccount();
    }

    @Override
    protected View onCreateDialogView() {

    	updateAccount();

    	return super.onCreateDialogView();
    }



    private void updateAccount() {
    	AccountManager accountManager = AccountManager.get(this.getContext());
        Account[] accounts = accountManager.getAccountsByType("com.google");
        String[] values = new String[accounts.length];
     	for(int i = 0; i < accounts.length; i++) {
     		values[i] = accounts[i].name;
         }

         setEntryValues(values);
         setEntries(values);
         setDefaultValue( values.length == 1 ? values[0] :  "" ); //if there's only one account, automatically select it.
    }

	@Override
    protected void onClick()
	{
		AccountManager accountManager = AccountManager.get(this.getContext());
        Account[] accounts = accountManager.getAccountsByType("com.google");
        if(accounts.length > 0) {
        	super.onClick();
        } else {
        	Intent intent = new Intent();
       	    intent.setClassName( "com.google.android.gsf", "com.google.android.gsf.login.AccountIntroActivity" );

       	    if(getContext().getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
       	    	getContext().startActivity( intent );
       	    } else {
       	    	getContext().startActivity(new Intent(Settings.ACTION_ADD_ACCOUNT));
       	    }
        }
	}


	@Override
	protected boolean shouldPersist() {
		return true;
	}

}
